package org.test.bookpub;

import org.apache.catalina.connector.Connector;
import org.apache.catalina.filters.RemoteIpFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerFactory;
import org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.PathMatchConfigurer;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.test.bookpub.formatters.BookFormatter;
import org.test.bookpub.repository.BookRepository;

import javax.annotation.Resource;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

//import org.apache.catalina.filters.RemoteIpFilter;

@Configuration
@PropertySource("classpath:/tomcat.https.properties")
@EnableConfigurationProperties(WebConfiguration.TomcatSslConnectorProperties.class)
@EnableScheduling
public class WebConfiguration extends WebMvcConfigurerAdapter {
    @Autowired
    private BookRepository bookRepository;

   @Bean
    public RemoteIpFilter remoteIpFilter() {
        return new RemoteIpFilter();
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        return new LocaleChangeInterceptor();
    }

    /**
     * 项目启动初始化一些东西，可以放在StartupRunner里运行。
     */
    @Bean
    public StartupRunner schedulerRunner() {
        return new StartupRunner();
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }

    @Bean
    public ByteArrayHttpMessageConverter byteArrayHttpMessageConverter() {
        return new ByteArrayHttpMessageConverter();
    }

//    This code is commented out because it was used only as an example, but actually breaks the data rendering.
//    @Override
//    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//        converters.clear();
//        converters.add(new ByteArrayHttpMessageConverter());
//    }

    /**
     * 注册一个全局“参数解析器”，比如把某对象的ID转换成这个对象本身。
     * 这个解析器是是全局有效的，在所有Controller中都可以使用。
     * 普通类型的、单个Controller有效，建议在单个Controller有效中使用@InitBinder绑定PropertyEditor
     *
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addFormatter(new BookFormatter(bookRepository));
    }

    /**
     * 配置url参数的匹配符
     * 例如url.*和url是否通用，url和url/是否通用
     *
     * @param configurer
     */
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false).setUseTrailingSlashMatch(false);
    }

    /**
     * 配置静态资源的访问路径(可以设置多个)
     * 两个*号表示递归查找子文件夹
     *
     * @param registry
     */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //可以设置多个Handler
      /*  registry.addResourceHandler("/internal")
                .addResourceLocations("classpath:/");*/
        registry
                .addResourceHandler("/static/**")
                .addResourceLocations("classpath:/")
                //设置多个，按照加入顺序查找
                .addResourceLocations("classpath:/static/")
        //.setCachePeriod(10000)//设置对本资源的缓存时间
        ;
    }

    /*
    * 设置HTTPSESSION的超时时间
    * */
    @Bean
   /* public EmbeddedServletContainerCustomizer
    embeddedServletContainerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {
            @Override
            public void
            customize(ConfigurableEmbeddedServletContainer
                              container) {
                container.setSessionTimeout(1, TimeUnit.MINUTES);
            }
        };
    }*/
    /*JAVA8的lambda表达式实现*/
    public EmbeddedServletContainerCustomizer
    embeddedServletContainerCustomizer() {
        List l=new ArrayList();
        l.stream();
        return (ConfigurableEmbeddedServletContainer container) -> {
            container.setSessionTimeout(1, TimeUnit.MINUTES);
        };
    }

    @Bean
    public EmbeddedServletContainerFactory servletContainer(TomcatSslConnectorProperties properties) {
        TomcatEmbeddedServletContainerFactory tomcat = new TomcatEmbeddedServletContainerFactory();
        tomcat.addAdditionalTomcatConnectors(properties.configureConnector(new Connector()));
        return tomcat;
    }

    @ConfigurationProperties(prefix = "custom.tomcat.https")
    public static class TomcatSslConnectorProperties {
        private Integer port;
        private Boolean ssl= true;
        private Boolean secure = true;
        private String scheme = "https";
        private File keystore;
        private String keystorePassword;

        public Integer getPort() {
            return port;
        }

        public void setPort(Integer port) {
            this.port = port;
        }

        public Boolean getSsl() {
            return ssl;
        }

        public void setSsl(Boolean ssl) {
            this.ssl = ssl;
        }

        public Boolean getSecure() {
            return secure;
        }

        public void setSecure(Boolean secure) {
            this.secure = secure;
        }

        public String getScheme() {
            return scheme;
        }

        public void setScheme(String scheme) {
            this.scheme = scheme;
        }

        public File getKeystore() {
            return keystore;
        }

        public void setKeystore(File keystore) {
            this.keystore = keystore;
        }

        public String getKeystorePassword() {
            return keystorePassword;
        }

        public void setKeystorePassword(String keystorePassword) {
            this.keystorePassword = keystorePassword;
        }

        public Connector configureConnector(Connector connector) {
            if (port != null)
                connector.setPort(port);
            if (secure != null)
                connector.setSecure(secure);
            if (scheme != null)
                connector.setScheme(scheme);
            if (ssl!= null)
                connector.setProperty("SSLEnabled", ssl.toString());
            if (keystore!= null && keystore.exists()) {
                connector.setProperty("keystoreFile",
                        keystore.getAbsolutePath());
                connector.setProperty("keystorePassword", keystorePassword);
            }
            return connector;
        }
    }

}
